//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System.Globalization;
using System;
using System.Configuration.Install;
using System.Windows.Forms;
using System.IO;

namespace TridentDbInstaller
{
    partial class TridentDbInstaller
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

		// Project specific settings -- START ----------------------
		private const string PROJECT_NAME = "Trident";
		// Project specific settings -- END ------------------------

		private const string APPLICATION_PREFIX = "Application";

		private const string ConfigFileMask = @"{0}\Research\" + PROJECT_NAME + @"\ConnStore-{1}.configSources";

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code


        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
        }

        public override void Install(System.Collections.IDictionary stateSaver)
        {
            try
            {				
                TriDbError status = TriDbError.ServerConnFailed;
                //Take all the parameters              
                string dbInstallAction = Context.Parameters["installaction"].ToString();
                string databaseServerName = Context.Parameters["dbserver"].ToString();
                string databaseName = Context.Parameters["dbname"].ToString();
                string dbScriptfolder = Context.Parameters["scriptfolder"].ToString();
                string dboverride = Convert.ToString(Context.Parameters["dboverride"]);
                bool dbinstall = Convert.ToBoolean(Context.Parameters["dbinstall"]);
				int authentication = Convert.ToInt32(Context.Parameters["dbauthentication"]);
				string dbUser = Convert.ToString(Context.Parameters["dbuser"]);
				string password = Convert.ToString(Context.Parameters["dbpassword"]);				

				// Deletes the config file in App Data
				this.DeleteConfigFile();

                // This is to make sure we have the dataBase server name in format localhost\SqlIntanceName
                if (databaseServerName.Contains(@"\\"))
                {
                    databaseServerName = databaseServerName.Replace(@"\\", @"\");
                }

				if (dbinstall)
                {
					InstallDB installObj = new InstallDB(Context, dbUser, password, authentication);
                    TridbAction dbAction = (TridbAction)Convert.ToInt32(dbInstallAction);
					status = installObj.ManageSqlDataBase(dbAction, dbScriptfolder, databaseServerName, databaseName);
                    if (TriDbError.ErrorSuccess != status)
                    {
                        switch (status)
                        {
                            case TriDbError.DatabaseExists:
                                {
                                    // Override DB only if opted
                                    if (!string.IsNullOrEmpty(dboverride))
                                    {
                                        status = installObj.ManageSqlDataBase(TridbAction.ReCreate, dbScriptfolder, databaseServerName, databaseName);
                                    }
                                    //Add registry configuration for the db created
									InstallConnectionSettings.AddConfiguration(databaseServerName, databaseName, dbUser, password, authentication);

                                    break;
                                }
                            case TriDbError.ScriptExecError:
                                {
                                    base.Rollback(stateSaver);
                                    break;
                                }
                            case TriDbError.ServerConnFailed:
                                {
                                    base.Rollback(stateSaver);
                                    break;
                                }
                            default:                                
                                base.Rollback(stateSaver);
                                break;

                        }
                    }
                    else
                    {
                        //Add registry configuration for the db created
						InstallConnectionSettings.AddConfiguration(databaseServerName, databaseName, dbUser, password, authentication);
                    }
                }
                else
                {
					InstallConnectionSettings.AddConfiguration(databaseServerName, databaseName, dbUser, password, authentication);
                }
                base.Install(stateSaver);
            }
            catch (Exception exp)
            {	
				Context.LogMessage(exp.Message);
				Context.LogMessage(exp.StackTrace);
				if (null != exp.InnerException)
				{
					Context.LogMessage(exp.InnerException.Message);
					Context.LogMessage(exp.InnerException.StackTrace);
				}
				throw exp;                
            }
        }

		/// <summary>
		/// Deletes the config file (if found to exist) in the user's App Data.
		/// </summary>
		private void DeleteConfigFile()
		{
			Environment.SpecialFolder folder = Environment.SpecialFolder.ApplicationData;
			
			string appFolder = System.Environment.GetFolderPath(folder);
			string defaultConfigFile = string.Format(ConfigFileMask, appFolder, APPLICATION_PREFIX);			

			// Delete if the file exists in the app folder of the user.
			if (File.Exists(defaultConfigFile))
			{
				try
				{
					// Delete the file
					File.Delete(defaultConfigFile);
				}
				catch (Exception exp)
				{
					Context.LogMessage(exp.Message);
					Context.LogMessage(exp.StackTrace);
					if (null != exp.InnerException)
					{
						Context.LogMessage(exp.InnerException.Message);
						Context.LogMessage(exp.InnerException.StackTrace);
					}
					throw exp;
				}
			}			
		}

        private void MessageBox(string p)
        {
			throw new NotImplementedException();
        }

        #endregion
    }
}